package com.woniu.liuzhougov.authorityControl.service.impl;

import com.woniu.liuzhougov.authorityControl.dao.RoleRightsMapper;
import com.woniu.liuzhougov.authorityControl.service.RoleRightsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author zhuxinpan
 * @version 1.0
 * @className RoleRightsService
 * @description 处理角色权限中间表的业务
 * @date 2019/4/29 20:11
 */
@Service
public class RoleRightsServiceImpl implements RoleRightsService {
    @Resource
    private RoleRightsMapper roleRightsMapper;

    /**
     * @param rightsId
     * @return int
     * @author zhuxinpan
     * @date 2019/4/29 20:09
     * @description 通过权限id查找使用数量
     */
    @Override
    public int countNumberByRightsId(Integer rightsId) {
        return roleRightsMapper.countNumberByRightsId(rightsId);
    }

    /**
     * @param roleId
     * @return java.util.List<java.lang.Integer>
     * @author zhuxinpan
     * @date 2019/4/29 20:39
     * @description 列出角色的选中id
     */
    @Override
    public List<Integer> listRightsIdByRoleId(Integer roleId) {
        return roleRightsMapper.listRightsIdByRoleId(roleId);
    }

    /**
     * @param roleId
     * @param rightsIds
     * @return int
     * @author zhuxinpan
     * @date 2019/4/29 21:05
     * @description 设置角色权限
     */
    @Override
    public int setAuthorization(Integer roleId, Integer[] rightsIds) {
        //修改前的权限集合
        Set<Integer> oldRightsIds = new HashSet<>(listRightsIdByRoleId(roleId));
        //修改后的权限集合
        Set<Integer> newRightsIds = new HashSet<>(Arrays.asList(rightsIds));
        //要移除的权限id集合
        Set<Integer> removeRightsIds = new HashSet<>();
        //先将之前的集合放入,再移除新集合的元素,就是需要删除的集合id
        removeRightsIds.addAll(oldRightsIds);
        removeRightsIds.removeAll(newRightsIds);
        //要添加的权限id集合
        //与上面相反的思路
        Set<Integer> addRightsIds = new HashSet<>();
        addRightsIds.addAll(newRightsIds);
        addRightsIds.removeAll(oldRightsIds);
        int result = 0;
        if (removeRightsIds.size() > 0) {
            result += roleRightsMapper.deleteByRoleId(roleId, removeRightsIds);
        }
        if (addRightsIds.size() > 0) {
            result += roleRightsMapper.insertByRoleId(roleId, addRightsIds);
        }
        return result;
    }

    /**
     * @param roleId
     * @return int
     * @author zhuxinpan
     * @date 2019/4/30 9:32
     * @description 通过角色id统计数量
     */
    @Override
    public int countNumberByRoleId(Integer roleId) {
        return roleRightsMapper.countNumberByRoleId(roleId);
    }

}
